import { defineStore } from "pinia";
import { reqLogin, reqUserInfo } from "../../api/user";
import type { loginFormData, loginResponseData } from "../../api/user/type";
import type { userState } from "./type/user";
import { commentRoutes } from "../../router/routes";

let useUserStore = defineStore('user', {
  state: (): userState => {
    return {
      token: localStorage.getItem('token'),
      // @ts-ignore
      menuRoutes: commentRoutes,
      username: '',
      avatar: ''
    }
  },
  actions: {
    async userLogin(data: loginFormData) {
      let res: loginResponseData = await reqLogin(data)
      if (res.code === 200) {
        this.token = res.data.token
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data.message))
      }
    },
    async userInfo() {
      let res = await reqUserInfo()
      if (res.code === 200) {
        this.username = res.data.checkUser.username
        this.avatar = res.data.checkUser.avatar
        console.log(res)
      }
    },
    userLogout() {
      localStorage.removeItem('token');
      this.token = ''
      this.username = ''
      this.avatar = ''
    }
  },
  getters: {

  },
  persist: {
    key: 'token',
    storage: localStorage,
  }
})

export default useUserStore